﻿//-----------------------------------------------------------------------
//  This file is part of the Microsoft Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//-----------------------------------------------------------------------

#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Configuration;
using System.Xml;
using System.Diagnostics;
using RetailAnalytic.Tools.ActivitySystem;

#endregion

namespace RetailAnalytic.Tools.ActivitySystem
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1301:AvoidDuplicateAccelerators")]
    public partial class MainForm : UserControl 
    {
        public enum ImageListItems { ClosedFolder = 0, OpenFolder, Lock, Connection, ServerConnected, ServerDisconnected, Explorer };
        private enum AppNodeType { Undefined = 0, Group, Server, Connections, Sessions, Transactions, Locks };

        private const string KEY_COLUMN_CONNECTIONS = "CONNECTION_ID";
        private const string KEY_COLUMN_SESSIONS = "SESSION_ID";
        private const string KEY_COLUMN_SESSIONS_SPID = "SESSION_SPID";
        private const string KEY_COLUMN_TRANSACTIONS = "TRANSACTION_ID";
        //private const string KEY_COLUMN_LOCKS = "LOCK_ID";

        private Utilities _utils = new Utilities();
        private int _selectedRow = -1;
        private string _selectedServer = string.Empty;
        private string _currentDiscoverType = ASCommands.DiscoverTypeNone;
        public string _Server;
        public MainForm(string Server  )
        {
            /// _Server - Name monitor AS Server


            _Server = Server;
            InitializeComponent();
            SetGuiAppearance();
        }
        private void SetGuiAppearance()
        {
            tvObjects.ImageList = this.images;
            this.images.Images.Clear();
            this.images.Images.Add("0", SR.ImagesLibrary.GetImageByName("close"));
            this.images.Images.Add("1", SR.ImagesLibrary.GetImageByName("open"));
            this.images.Images.Add("2", SR.ImagesLibrary.GetImageByName("SECUR"));
            this.images.Images.Add("3", SR.ImagesLibrary.GetImageByName("NET08"));
            this.images.Images.Add("4", SR.ImagesLibrary.GetImageByName("L_Cube_16"));
            this.images.Images.Add("5", SR.ImagesLibrary.GetImageByName("L_Cube_16"));
            this.images.Images.Add("6", SR.ImagesLibrary.GetImageByName("EXPLORER"));
        }

        #region Form Events
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void MainForm_Load(object sender, EventArgs e)
        {
            string timerInterval;
            //Load the list of registered servers
            try
            {
                //XmlNodeList servers = Utilities.GetServers();
                string servers = _Server;
                //foreach (XmlNode node in servers)
                //    LoadServerNode(node, null);
                LoadServerNode(servers, null);
                
            }
            catch (Exception ex)
            {
                DisplayMessage("Unable to load the list of registered servers.\n"
                    + ex.Message, "Application Error", MessageBoxIcon.Error);
            }
            ConnectServer(_Server);
            try
            {
                timerInterval
                    = Properties.Settings.Default.MonitorPollIntervalSeconds;
                bgTimer.Interval = int.Parse(timerInterval,
                    System.Globalization.CultureInfo.InvariantCulture) * 1000;
                if (bgTimer.Interval < 0 || bgTimer.Interval > 60000)
                {
                    bgTimer.Interval = 5000;
                }
            }
            catch (System.Exception ex)
            {
                DisplayMessage("Unable to load configuration settings.\n"
                    + ex.Message, "Application Error", MessageBoxIcon.Error);
            }

            ClearTreeViewSelection();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            bgTimer.Enabled = false;
            if (_utils != null)
            {
                _utils.Dispose();
            }
        }

        #endregion

        #region TreeView Events

        private void tvObjects_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            AppNodeType nodeType = GetNodeType(e.Node);

            //if moving to a node away from selected server, clear the grid
            if (nodeType == AppNodeType.Server)
            {
                SetSelectedServer(e.Node.Text);
            }
            else if (nodeType == AppNodeType.Group)
            {
                SetSelectedServer(string.Empty);
            }
            else if (_selectedServer != e.Node.Parent.Text)
            {
                SetSelectedServer(e.Node.Parent.Text);
            }

            if (e.Button == MouseButtons.Left)
            {
                switch (nodeType)
                {
                    case AppNodeType.Server:
                        {
                            ASCommands obj
                                = _utils.GetValidASCommandObject(_selectedServer);
                            if (obj.IsConnected && e.Node.Nodes.Count == 0)
                            {
                                AddChildActionNodes(e.Node);
                                e.Node.Expand();
                            }
                            else
                            {
                                if (e.Node.IsExpanded && e.Node.IsSelected)
                                {
                                    e.Node.Collapse();
                                }
                                else if (obj.IsConnected)
                                {
                                    e.Node.Expand();
                                }
                            }
                            break;
                        }
                    case AppNodeType.Group:
                        {
                            if (e.Node.IsExpanded && e.Node.IsSelected)
                            {
                                e.Node.Collapse();
                            }
                            else
                            {
                                e.Node.Expand();
                            }

                            break;
                        }
                    default:
                        {
                            DoDiscoverNodeSelection(nodeType);
                            break;
                        }
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                if (nodeType == AppNodeType.Group)
                {
                    return;
                }

                //force node to be selected
                tvObjects.SelectedNode = e.Node;

                //show the context menu
                DisplayNodeContextMenu(nodeType);
            }
        }
        #endregion

        #region Grid Events

        private void grdResults_MouseUp(object sender, MouseEventArgs e)
        {
            Point pt = grdResults.PointToClient(Control.MousePosition);
            DataGridView.HitTestInfo hti = grdResults.HitTest(pt.X, pt.Y);
            if (hti.RowIndex >= 0 && e.Button == MouseButtons.Right)
            {
                grdResults.ClearSelection();
                grdResults.Rows[hti.RowIndex].Selected = true;

                //record which row is now the currently selected row
                _selectedRow = hti.RowIndex;

                if (_currentDiscoverType != ASCommands.DiscoverTypeLocks)
                {
                    cmGrid.Show(grdResults, pt);
                }
            }
        }

        private void grdResults_Sorted(object sender, EventArgs e)
        {
            SetSpecialRowForeColor(_currentDiscoverType);
        }
        #endregion

        #region Context Menu Events: Servers

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public void ConnectServer(string Server)
        { 
            ASCommands obj = _utils.GetValidASCommandObject(Server);

            tvObjects.Refresh();
            grdResults.Refresh();
            if (!obj.IsConnected)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    obj.Connect();
                    tvObjects.Nodes[0].SelectedImageIndex = (int)ImageListItems.ServerConnected;
                    AddChildActionNodes(tvObjects.Nodes[0]);
                    tvObjects.Nodes[0].Expand();
                }
                catch (Exception ex)
                {
                    DisplayMessage("Error connecting to server.\n"
                        + ex.Message, "Application Error", MessageBoxIcon.Error);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }
        private void cmServersConnect_Click(object sender, EventArgs e)
        {
            ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);

            tvObjects.Refresh();
            grdResults.Refresh();
            if (!obj.IsConnected)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    obj.Connect();
                    tvObjects.SelectedNode.SelectedImageIndex
                        = (int)ImageListItems.ServerConnected;
                    AddChildActionNodes(tvObjects.SelectedNode);
                    tvObjects.SelectedNode.Expand();
                }
                catch (Exception ex)
                {
                    DisplayMessage("Error connecting to server.\n"
                        + ex.Message, "Application Error", MessageBoxIcon.Error);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }

        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmServersDisconnect_Click(object sender, EventArgs e)
        {
            ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);

            tvObjects.Refresh();
            grdResults.Refresh();
            if (obj.IsConnected)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;
                    obj.Disconnect();
                    tvObjects.SelectedNode.SelectedImageIndex
                        = (int)ImageListItems.ServerDisconnected;
                    tvObjects.SelectedNode.Collapse();
                    grdResults.DataSource = null;
                }
                catch (System.Exception ex)
                {
                    DisplayMessage(ex);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }

            }

        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmServersNodeRefresh_Click(object sender, EventArgs e)
        {
            if (tvObjects.SelectedNode != null)
            {
                try
                {
                    DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
                }
                catch (Exception ex)
                {
                    DisplayMessage(ex);
                }
            }
        }

        #endregion

        #region Context Menu Events: Grid
        private void cmGrid_Opened(object sender, EventArgs e)
        {
            cmGridCancelSession.Visible = false;
            cmGridCancelConnection.Visible = false;
            cmGridCancelTransaction.Visible = false;
            cmGridShowSessions.Visible = false;
            cmGridShowTransactions.Visible = false;
            cmGridShowLocks.Visible = false;

            switch (_currentDiscoverType)
            {
                case ASCommands.DiscoverTypeConnections:
                    cmGridCancelConnection.Visible = true;
                    cmGridShowSessions.Visible = true;
                    break;

                case ASCommands.DiscoverTypeSessions:
                    cmGridCancelSession.Visible = true;
                    cmGridShowTransactions.Visible = true;
                    break;

                case ASCommands.DiscoverTypeTransactions:
                    //cmGridCancelTransaction.Visible = true;
                    cmGridShowLocks.Visible = true;
                    break;

                default:
                    break;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridShowSessions_Click(object sender, EventArgs e)
        {
            try
            {
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);
                DataTable dt = obj.DiscoverSessions((int)
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_CONNECTIONS].Value);
                LoadGrid(dt, ASCommands.DiscoverTypeSessions);
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridShowTransactions_Click(object sender, EventArgs e)
        {
            try
            {
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);
                DataTable dt = obj.DiscoverTransactions(
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_SESSIONS].Value.ToString());
                LoadGrid(dt, ASCommands.DiscoverTypeTransactions);
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridShowLocks_Click(object sender, EventArgs e)
        {
            try
            {
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);
                DataTable dt = obj.DiscoverLocks(
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_TRANSACTIONS].Value.ToString());
                LoadGrid(dt, ASCommands.DiscoverTypeLocks);
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelConnection_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);
                obj.KillConnection((int)
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_CONNECTIONS].Value);
                MonitoredItem item = new MonitoredItem(
                    MonitoredItems.MonitoredItemType.Connection,
                    MonitoredItems.MonitoredItemAction.Cancel,
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_CONNECTIONS].Value,
                    _selectedServer);
                Utilities.LogActivityItemBegin(item);
                MonitoredItems.Add(item);

                //refresh the grid
                DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelSession_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);
                if (!obj.IsApplicationSession(
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_SESSIONS].Value.ToString()))
                {
                    obj.KillSession(
                        grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_SESSIONS].Value.ToString(),
                        (int)grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_SESSIONS_SPID].Value);
                    MonitoredItem item = new MonitoredItem(MonitoredItems.MonitoredItemType.Session,
                        MonitoredItems.MonitoredItemAction.Cancel,
                        grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_SESSIONS_SPID].Value,
                        _selectedServer);
                    item.AdditionalData.Add(
                        grdResults.Rows[_selectedRow].Cells["SESSION_USER_NAME"].Value.ToString());
                    item.AdditionalData.Add(
                        grdResults.Rows[_selectedRow].Cells["SESSION_ID"].Value.ToString());
                    Utilities.LogActivityItemBegin(item);
                    MonitoredItems.Add(item);

                    //refresh the grid
                    DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
                }
                else
                {
                    DisplayMessage("The selected session is in use by this application and can not be cancelled.", "Session In Use", MessageBoxIcon.Exclamation);
                }
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
            finally { this.Cursor = Cursors.Default; }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void cmGridCancelTransaction_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);
                obj.KillTransaction(
                    grdResults.Rows[_selectedRow].Cells[KEY_COLUMN_TRANSACTIONS].Value.ToString());

                //refresh the grid
                DoDiscoverNodeSelection((AppNodeType)tvObjects.SelectedNode.Tag);
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
            finally { this.Cursor = Cursors.Default; }

        }
        #endregion

        #region Private support methods
        private void LoadServerNode(string node, TreeNode parent)
        {
            TreeNode tn = null;
           
              tn = new TreeNode(node,
                  (int)ImageListItems.ServerConnected, (int)ImageListItems.ServerConnected);
              tn.Tag = AppNodeType.Server;
            

            if (tn != null)
            {
                if (parent == null)
                {
                    tvObjects.Nodes.Add(tn);
                }
                else
                {
                    parent.Nodes.Add(tn);
                }

            //    if ((AppNodeType)tn.Tag == AppNodeType.Group
            //        && node.ChildNodes.Count > 0)
            //    {
            //        foreach (XmlNode child in node.ChildNodes)
            //        {
            //            LoadServerNode(child, tn);
            //        }
            //    }
            }
        }

        private void SetSelectedServer(string selectedServer)
        {
            if (_selectedServer != selectedServer
                || selectedServer.Length == 0)
            {
                _selectedServer = selectedServer;
                grdResults.DataSource = null;
                lblDisplayedServer.Text = string.Empty;
            }
        }

        private void DisplayNodeContextMenu(AppNodeType nodeType)
        {
            foreach (ToolStripItem item in cmServers.Items)
            {
                item.Visible = item.Enabled = false;
            }
            if (nodeType == AppNodeType.Server)
            {
                ASCommands obj
                    = _utils.GetValidASCommandObject(_selectedServer);
                if (obj.IsConnected)
                {
                    cmServersConnect.Visible = true;
                    cmServersDisconnect.Visible
                        = cmServersDisconnect.Enabled = true;
                }
                else
                {
                    cmServersConnect.Visible = cmServersConnect.Enabled = true;
                    cmServersDisconnect.Visible = true;
                }
            }
            else
            {
                cmServersNodeRefresh.Visible
                    = cmServersNodeRefresh.Enabled = true;
            }

            //display context menu
            Point pt = tvObjects.PointToClient(Control.MousePosition);
            cmServers.Show(tvObjects, pt);
        }

        private void AddChildActionNodes(TreeNode node)
        {
            if (node.Nodes.Count > 0)
            {
                return;
            }

            tvObjects.SuspendLayout();
            TreeNode tn = new TreeNode(ASCommands.DiscoverNameConnections,
                (int)ImageListItems.Connection,
                (int)ImageListItems.Connection);
            tn.Tag = AppNodeType.Connections;
            node.Nodes.Add(tn);

            tn = new TreeNode(ASCommands.DiscoverNameSessions,
                (int)ImageListItems.Explorer, (int)ImageListItems.Explorer);
            tn.Tag = AppNodeType.Sessions;
            node.Nodes.Add(tn);

            tn = new TreeNode(ASCommands.DiscoverNameTransactions,
                (int)ImageListItems.Explorer, (int)ImageListItems.Explorer);
            tn.Tag = AppNodeType.Transactions;
            node.Nodes.Add(tn);

            tn = new TreeNode(ASCommands.DiscoverNameLocks,
                (int)ImageListItems.Lock, (int)ImageListItems.Lock);
            tn.Tag = AppNodeType.Locks;
            node.Nodes.Add(tn);

            tvObjects.ResumeLayout();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void DoDiscoverNodeSelection(AppNodeType nodeType)
        {
            DataTable dt = null;
            string discoverType = ASCommands.DiscoverTypeNone; ;

            this.Cursor = Cursors.WaitCursor;

            try
            {
                ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);

                //find out which node was selected
                switch (nodeType)
                {
                    case AppNodeType.Connections:
                        dt = obj.DiscoverConnections();
                        discoverType = ASCommands.DiscoverTypeConnections;
                        break;

                    case AppNodeType.Sessions:
                        dt = obj.DiscoverSessions();
                        discoverType = ASCommands.DiscoverTypeSessions;
                        break;

                    case AppNodeType.Transactions:
                        dt = obj.DiscoverTransactions();
                        discoverType = ASCommands.DiscoverTypeTransactions;
                        break;

                    case AppNodeType.Locks:
                        dt = obj.DiscoverLocks();
                        discoverType = ASCommands.DiscoverTypeLocks;
                        break;
                }

                LoadGrid(dt, discoverType);
            }
            catch (Exception ex)
            {
                DisplayMessage(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private bool LoadGrid(DataTable dataTable, string discoverType)
        {
            try
            {
                grdResults.SuspendLayout();

                //clear the grid
                grdResults.DataSource = null;
                _selectedRow = -1;

                //Load new data
                lblDisplayedServer.Visible = true;
                lblDisplayedServer.Text = _selectedServer;
                _currentDiscoverType = discoverType;
                grdResults.DataSource = dataTable;
                grdResults.AutoResizeColumns(
                    DataGridViewAutoSizeColumnsMode.ColumnHeader);

                //Set column display order
                SetColumnDisplayOrder();

                //set ForeColor for rows that are in the monitored items collection
                //or are sessions tied to this application
                SetSpecialRowForeColor(discoverType);

                return true;
            }
            catch (Exception ex)
            {
                DisplayMessage(ex);
                return false;
            }
            finally
            {
                grdResults.ResumeLayout();
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void SetSpecialRowForeColor(string discoverType)
        {
            MonitoredItem item = null;
            ASCommands obj = _utils.GetValidASCommandObject(_selectedServer);

            for (int row = 0; row < grdResults.Rows.Count; row++)
            {
                //check for connections/sessions created by this application
                switch (discoverType)
                {
                    case ASCommands.DiscoverTypeSessions:
                        if (obj.IsApplicationSession(
                            grdResults.Rows[row].Cells[KEY_COLUMN_SESSIONS].Value.ToString()))
                        {
                            grdResults.Rows[row].DefaultCellStyle.ForeColor = Color.Gray;
                        }

                        break;

                    case ASCommands.DiscoverTypeConnections:
                        if (obj.IsApplicationConnection(
                            grdResults.Rows[row].Cells[KEY_COLUMN_CONNECTIONS].Value.ToString()))
                        {
                            grdResults.Rows[row].DefaultCellStyle.ForeColor = Color.Gray;
                        }

                        break;
                }

                //if we've set the row or there are no monitored items, move on to the next row
                if (grdResults.Rows[row].DefaultCellStyle.ForeColor == Color.Gray || MonitoredItems.Count == 0)
                {
                    continue;
                }

                //check for monitored items
                for (int i = 0; i < MonitoredItems.Count; i++)
                {
                    try { item = MonitoredItems.Item(i); }
                    catch { break; }

                    switch (discoverType)
                    {
                        case ASCommands.DiscoverTypeConnections:
                            if (item.ItemType == MonitoredItems.MonitoredItemType.Connection
                                && item.ItemValue.ToString()
                                == grdResults.Rows[row].Cells[KEY_COLUMN_CONNECTIONS].Value.ToString())
                            {
                                grdResults.Rows[row].DefaultCellStyle.ForeColor = Color.Gray;
                            }

                            break;

                        case ASCommands.DiscoverTypeSessions:
                            if (item.ItemType == MonitoredItems.MonitoredItemType.Session
                                && item.ItemValue.ToString()
                                == grdResults.Rows[row].Cells[KEY_COLUMN_SESSIONS_SPID].Value.ToString())
                            {
                                grdResults.Rows[row].DefaultCellStyle.ForeColor = Color.Gray;
                            }

                            break;
                    }
                }
            }
        }

        private void SetColumnDisplayOrder()
        {
            switch (_currentDiscoverType)
            {
                case ASCommands.DiscoverTypeSessions:
                    grdResults.Columns["SESSION_SPID"].DisplayIndex = 0;
                    grdResults.Columns["SESSION_CONNECTION_ID"].DisplayIndex = 1;
                    grdResults.Columns["SESSION_USER_NAME"].DisplayIndex = 2;
                    grdResults.Columns["SESSION_CURRENT_DATABASE"].DisplayIndex = 3;
                    //grdResults.Columns["SESSION_LAST_REQUEST"].DisplayIndex = 4;
                    grdResults.Columns["SESSION_LAST_COMMAND_START_TIME"].DisplayIndex = 4;
                    grdResults.Columns["SESSION_LAST_COMMAND_ELAPSED_TIME_MS"].DisplayIndex = 5;
                    grdResults.Columns["SESSION_LAST_COMMAND_END_TIME"].DisplayIndex = 6;
                    grdResults.Columns["SESSION_CPU_TIME_MS"].DisplayIndex = 7;
                    grdResults.Columns["SESSION_START_TIME"].DisplayIndex = 8;
                    grdResults.Columns["SESSION_ELAPSED_TIME_MS"].DisplayIndex = 9;
                    grdResults.Columns["SESSION_IDLE_TIME_MS"].DisplayIndex = 10;
                    grdResults.Columns["SESSION_USED_MEMORY"].DisplayIndex = 11;
                    grdResults.Columns["SESSION_PROPERTIES"].DisplayIndex = 12;
                    grdResults.Columns["SESSION_ID"].DisplayIndex = 13;
                    break;

                case ASCommands.DiscoverTypeConnections:
                    break;

                default:
                    break;
            }
        }

        private static AppNodeType GetNodeType(TreeNode node)
        {
            if (node.Tag != null && node.Tag is AppNodeType)
            {
                return (AppNodeType)node.Tag;
            }
            else
            {
                return AppNodeType.Undefined;
            }
        }

        private void ClearTreeViewSelection()
        {
            lblDisplayedServer.Text = string.Empty;
            grdResults.DataSource = null;
            tvObjects.SelectedNode = null;
        }

        private void DisplayMessage(string message, string caption, MessageBoxIcon icon)
        {
            RetailAnalytic.Core.Dialog.Show(RetailAnalytic.Core.Dialog_type.Information,SR.StringLibrary.GetStrMSG(SR.StringLibrary.KeyEnum.MESSAGE_EMPTY,
                Environment.StackTrace, message));

            //MessageBox.
            //    Show(this, message, caption, MessageBoxButtons.OK, icon,
            //    MessageBoxDefaultButton.Button1, 0);
        }

        private void DisplayMessage(System.Exception ex)
        {
            string message = ex.Message;
            if (ex.InnerException != null)
            {
                message += "\n" + ex.InnerException.Message;
            }
            string finalMessage = "An error has occurred in the application: \n\n" + message;
            RetailAnalytic.Core.Dialog.Show(RetailAnalytic.Core.Dialog_type.Information, SR.StringLibrary.GetStrMSG(SR.StringLibrary.KeyEnum.MESSAGE_EMPTY, 
                Environment.StackTrace, finalMessage));

            //MessageBox.
            //    Show(this, finalMessage, "Application Error",
            //    MessageBoxButtons.OK, MessageBoxIcon.Error,
            //    MessageBoxDefaultButton.Button1, 0);
        }
        #endregion

        #region BackgroundWorker

        private void bgwCancelMonitor_DoWork(object sender, DoWorkEventArgs e)
        {
            // This method will run on a thread other than the UI thread.
            // Be sure not to manipulate any Windows Forms controls created
            // on the UI thread from this method.
        }

        #endregion

        #region Control Events

        private void bgTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                bgwCancelMonitor.RunWorkerAsync();
            }
            catch { }
        }

        #endregion

        #region ToolStrip Menu Events

        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (grdResults.DataSource == null)
            {
               // SaveAsToolStripMenuItem.Enabled = false;
            }
            else
            {
                //SaveAsToolStripMenuItem.Enabled = true;
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm frm = new AboutForm();
            frm.ShowDialog(this);
            frm.Dispose();
        }

       

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog.FileName = "*.txt";
                saveFileDialog.Filter
                    = "Tab Delimited(.txt)|.txt|Comma Delimited(.csv)|.csv";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.InitialDirectory = Application.ExecutablePath;

                if (saveFileDialog.ShowDialog(this) == DialogResult.Cancel)
                {
                    return;
                }

                string filePath = saveFileDialog.FileName;

                switch (saveFileDialog.FilterIndex)
                {
                    case 1:
                        Utilities.SaveDataTableToFile(
                            (DataTable)grdResults.DataSource, "\t", filePath);
                        break;

                    default:
                        Utilities.SaveDataTableToFile(
                            (DataTable)grdResults.DataSource, ",", filePath);
                        break;
                }
            }
            catch (System.Exception ex)
            {
                DisplayMessage(ex);
            }
        }
        #endregion
    }
}